package com.qingfeng.client.service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.qingfeng.client.bean.Buyer;
import com.qingfeng.client.dao.BuyerMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author ff
 * @Data 2017/10/27 14:43
 */
@Slf4j
@Service
public class BuyerService {

    @Value("${jwtTokenPeriodTime}")
    private Integer jwtTokenPeriodTime;

    @Resource
    private BuyerMapper buyerDao;

    @Autowired
    private RedisService redisService;


    public Buyer selectById(Long id){
        return buyerDao.selectById(id);
    }

    /**
     * 手机登陆
     *
     * @param phone
     * @param password
     * @return

     */
    public Buyer login(String phone, String password) {

        if (!StringUtils.isEmpty(phone) && !StringUtils.isEmpty(password)
                && isMobileNO(phone) && password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$")) {
            Buyer buyerBean = buyerDao.selectOneByPhone(phone);
            if (buyerBean != null && DigestUtils.md5DigestAsHex(password.getBytes()).equals(buyerBean.getPassword())) {
                //设置最后登陆时间
                buyerBean.setLastLoginTime(System.currentTimeMillis() / 1000);
                buyerBean.setToken(redisService.setToken(buyerBean));
                buyerDao.updateById(buyerBean);
                return buyerBean;
            }
        }
       return null;
    }


    /**
     * 判断是否11位手机号码
     *
     * @param mobiles
     * @return
     */
    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断邮箱是否正确
     *
     * @param email
     * @return
     */
    public boolean isEmailNO(String email) {
        Pattern p = Pattern.compile("^[a-z0-9]+([._\\\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
        Matcher m = p.matcher(email);
        return m.matches();
    }
}
